package com.edu.cqr.web.demo.controller;

import com.edu.cqr.web.demo.config.ResultJson;
import com.edu.cqr.web.demo.model.UserInfo;
import com.edu.cqr.web.demo.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;


@RestController
@RequestMapping("/user")
@Api(tags="用户管理")
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping("/login")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName",value = "用户名",dataType = "string",required = true),
            @ApiImplicitParam(name = "password",value = "密码",dataType = "string",required = true)
    })
    public ResultJson login(String userName,String password){
       try {
           UsernamePasswordToken token = new UsernamePasswordToken(userName,password);
           Subject subject = SecurityUtils.getSubject();
           subject.login(token);
           String sessionId = subject.getSession().getId().toString();
           HashMap<String,String> map = new HashMap<>();
           map.put("token",sessionId);
           return new ResultJson("200","登录成功！",map);
       }catch (UnknownAccountException e){
//           账号不存在
           return new ResultJson("400","用户名或密码错误！","null");
       }catch (DisabledAccountException e){
           return new ResultJson("400","该账号已被禁用!","null");
       }catch (IncorrectCredentialsException e){
           return new ResultJson("400","用户名或密码错误!","null");
       }catch (Exception e){
           return new ResultJson("400","未知错误,请联系管理管理员!","null");
       }
}

@GetMapping("/need_login")
public ResultJson needLogin(){
        return new ResultJson("400","请先登录！","null");
}

@GetMapping("/unauth")
public ResultJson unauth(){
        return new ResultJson("400","您不具备相应权限","null");
}

@GetMapping("/add_user")
    @ApiOperation("添加用户")
    //@RequiresAuthentication
@RequiresRoles(value = {"admin"},logical = Logical.OR)
@ApiImplicitParams({
        @ApiImplicitParam(name = "token",value = "鉴权Token",dataType = "String",required = true,paramType = "header"),
        @ApiImplicitParam(name = "userName",value = "用户名",dataType = "String",required = true),
        @ApiImplicitParam(name = "password",value = "密码",dataType = "String",required = true),
        @ApiImplicitParam(name = "roleName",value = "角色名",dataType = "String",required = true)
})
    public ResultJson addUser(String userName,String password,String roleName){
        try {
            userService.addUser(userName,password,roleName);
            return new ResultJson("200","添加用户成功!",null);
        }catch (Exception e){
            return new ResultJson("400","添加用户失败!",null);
        }
}

@GetMapping("/del_user")
    @ApiOperation("删除用户")
@ApiImplicitParams({
        @ApiImplicitParam(name = "token",value = "鉴权Token",dataType = "String",required = true,paramType = "header"),
        @ApiImplicitParam(name = "userName",value = "用户名",dataType = "String",required = true)
})
    public ResultJson DelUser(String userName){
    try {
        userService.delUser(userName);
        return new ResultJson("200","删除用户成功!",null);
    }catch (Exception e){
        return new ResultJson("400","删除用户失败!",null);
    }
}

@PostMapping("/reset_password")
    @ApiOperation("重置用户密码")
    @RequiresRoles(value={"admin"}, logical = Logical.OR)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "鉴权Token",dataType = "String",required = true,paramType = "header"),
            @ApiImplicitParam(name = "userName",value = "用户名",dataType = "String",required = true)
    })
    public ResultJson resetPassword(String userName){
        try {
            userService.modifyPassword(userName, "123456");
            return new ResultJson("400", "重置成功", null);
        }catch (Exception e){
            return new ResultJson("400","重置密码失败",null);
        }
        }

    @PostMapping("/reset_self_password")
    @ApiOperation("密码修改")
    @RequiresAuthentication
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "鉴权Token",dataType = "String",required = true,paramType = "header"),
            @ApiImplicitParam(name = "oldPwd",value = "旧密码",dataType = "String",required = true),
            @ApiImplicitParam(name = "password",value = "新密码",dataType = "String",required = true)
    })
    public ResultJson resetSelfPassword(String oldPwd,String password){
        Subject subject = SecurityUtils.getSubject();
        UserInfo userInfo = (UserInfo) subject.getPrincipals().getPrimaryPrincipal();
       if(userService.verifyPassword(oldPwd, userInfo.getSalt(),userInfo.getPassword())){
           try {
               userService.modifyPassword(userInfo.getUserName(),password);
               return new ResultJson("400","修改密码成功",password);
           }catch (Exception e){
               return new ResultJson("400","修改密码失败",null);
           }
       }else{
        return new ResultJson ("400","旧密码错误",null);
       }
    }
/**
 * 对用户状态改为禁止登录
 * */
    @PostMapping("/disableAccount_State")
    @ApiOperation("用户状态")
    @RequiresAuthentication
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "鉴权Token",dataType = "String",required = true,paramType = "header"),
            @ApiImplicitParam(name = "userName",value = "用户",dataType = "String",required = true)
    })
    @RequiresRoles(value={"admin"}, logical = Logical.OR)
    public ResultJson disableAccount(String userName){
        try{
            userService.updateState(userName);
            return new ResultJson("400","禁止成功",null);
        }catch (Exception e){
            return new ResultJson("400","禁止失败",null);
        }

/**
 * 将用户解除禁止登录
 * */
    }
    @PostMapping("/enableAccount_State")
    @ApiOperation("解除状态")
    @RequiresAuthentication
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "鉴权Token",dataType = "String",required = true,paramType = "header"),
            @ApiImplicitParam(name = "userName",value = "用户",dataType = "String",required = true)
    })
    @RequiresRoles(value={"admin"}, logical = Logical.OR)
    public ResultJson enableAccount(String userName){
        try{
            userService.enbupdateState(userName);
            return new ResultJson("400","解禁成功",null);
        }catch (Exception e){
            return new ResultJson("400","解禁失败",null);
        }
    }
/**
 *修改用户角色
 * */
    @PostMapping("/resetRoles")
    @ApiOperation("修改角色")
    @RequiresAuthentication
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "鉴权Token",dataType = "String",required = true,paramType = "header"),
            @ApiImplicitParam(name = "userName",value = "用户",dataType = "String",required = true),
            @ApiImplicitParam(name = "roleName",value = "角色",dataType = "String",required = true)
    })
    @RequiresRoles(value={"admin"}, logical = Logical.OR)
    public ResultJson resetRoles(String userName,String roleName){
        try {
            userService.updateRoles(userName,roleName);
            return new ResultJson("200","角色修改成功",null);
        }catch (Exception e) {
            return new ResultJson("400", "角色修改失败", null);
        }
    }

    /**
     * 查询个人信息
     * */
    @PostMapping("/QueryUser")
    @ApiOperation("个人信息查询")
    @RequiresAuthentication
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "鉴权Token",dataType = "String",required = true,paramType = "header")
    })
    @RequiresRoles(value={"admin"}, logical = Logical.OR)
    public ResultJson UserNameByUserInfo(){
        try{
            Subject subject = SecurityUtils.getSubject();
            UserInfo userInfo = (UserInfo) subject.getPrincipals().getPrimaryPrincipal();
            UserInfo userInfo1 = userService.findUserInfo(userInfo.getUserName());
            return new ResultJson("200","信息查询成功",userInfo1);
        }catch (Exception e) {
            return new ResultJson("400", "信息查询失败", null);
        }
    }

    /**
     * 查询用户详情信息
     * */
    @PostMapping("/QueryUserInfo")
    @ApiOperation("用户信息查询")
    @RequiresAuthentication
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "鉴权Token",dataType = "String",required = true,paramType = "header")
    })
    @RequiresRoles(value={"admin"}, logical = Logical.OR)
    public ResultJson findAllUserInfo(){
        try{
            List<UserInfo> userInfoAll = userService.findUserInfoAll();
            return new ResultJson("200","信息查询成功",userInfoAll);
        }catch (Exception e) {
            return new ResultJson("400", "信息查询失败", null);
        }
    }
}
